const settings = {editing_type: 'project', charts: {}};
const DEFAULT_IGNORED = '.git/;target/;*.iml;.gitignore;*.otf;*.ttf;*.png;*.eot;*.woff2;*.svg;*.woff';
const toolbar = (function ($) {
    let buttons = [], holder = {}, _defaultToEnable = [];
    return {
        init : function (selector, enabledList) {
            $(selector).each ((i, e) => {
                let x = $(e).addClass ('disabled'), id = x.attr ('id');
                buttons.push (x);
                holder[id] = x;

                Object.defineProperty (this, id, {
                    enumerable : true,
                    configurable : true,
                    get () { return holder[id]; }
                });
            });

            if (enabledList && enabledList.length) enabledList.forEach (name => {
                holder[name].removeClass ('disabled');
                _defaultToEnable.push (name);
            });
            return this;
        },
        enable: function (name) {
            if (name) {
                if (name in holder) {
                    holder[name].removeClass ('disabled');
                }
            } else {
                buttons.forEach (b => b.removeClass ('disabled'));
            }
        },
        disable: function (name) {
            if (name) {
                if (name in holder) {
                    holder[name].addClass ('disabled');
                }
            } else {
                buttons.forEach (b => b.addClass ('disabled'));
            }
        },
        reset: function () {
            buttons.forEach (b => b.addClass ('disabled'));
            if (_defaultToEnable.length) _defaultToEnable.forEach (name => holder[name].removeClass ('disabled'));
        },
        dispose: function () {
            buttons = [];
            holder = {};
            _defaultToEnable = [];
        }
    };
})(jQuery);

let project_selector = $('#choose-projects-dialog'),
    editor = $('#create-project-dialog'),
    project_pane = $('#project-info');
$(function () {
    toolbar.init ('.tool-bar-item', ['btn-create-project', 'btn-open-project']);

    update_ui ();

    // tool bar actions
    $('.tool-bar-item').on ('click', function () {
        if ($(this).hasClass ('disabled'))
            return;
        switch (this.id) {
            case 'btn-create-project':
            case 'btn-create-module':
                open_editor (this);
                break;

            case 'btn-open-project':
                choose_projects ();
                break;

            case 'btn-close-project':
                close_project ();
        }
    });

    // editors action
    $('#btn-select-project').on ('click', () => {
        let projectId = $('.list-item.selected').attr ('data-pid');
        if (projectId) {
            let project = bridge.require ('load-project', projectId);
            if (project) {
                close_project ();   // 先清除原有数据
                fill_project (settings.project = project);
                project_selector.modal ('hide');
            }
        }
    });
    $('#btn-browser').on ('click', () => {
        let c = $('#path'), path = c.val (), name = $('#item-name'), param = {type: settings.editing_type};
        if ($.trim (path)) {
            param.path = path;
        }
        path = bridge.require ('choose-dir', param);
        if (path) {
            c.val (path);

            if ($.trim (name.val ()) === '') {
                path = path.replace (/\\/g, '/');
                let index = path.lastIndexOf ('/');
                if (index >= 0) {
                    path = path.substring (index + 1);
                }
                name.val (path);
            }
        }
    });

    editor.on ('show.bs.modal', () => {
        let pattern = $('#ignore-pattern'), label = $('#label-include');
        $('#include-project').prop ('checked', true);
        $('#editor-error-message').text ('');
        if (settings.editing_type === 'project') {
            pattern.val (DEFAULT_IGNORED);
            label.hide ();
        } else {
            pattern.val ('');
            label.show ();
        }
    });

    $('#btn-save-edit').on ('click', () => {
        let type = settings.editing_type, project,
            handler = $('#editor-error-message'), progress = $('#editor-progress'),
            itemName = $('#item-name'), name = $.trim (itemName.val ()),
            location = $('#path'), path = $.trim (location.val ()),
            ignored = $('#ignore-pattern'), pattern = $.trim (ignored.val ());
            // checked = $('#include-project').prop ('checked');
        if (!name) {
            handler.show ().text ('请填写名称');
            return;
        }
        if (!path) {
            handler.show ().text ('请选择路径');
            return;
        }
        if (type === 'project') {
            handler.hide ();
            progress.show ();
            try {
                project = {name: name, path: path, pattern: pattern};
                let id = bridge.require ('save-project', project);
                if (id) {
                    project.id = id;
                    close_project ();
                    fill_project (settings.project = project);
                    editor.modal ('hide');
                } else {
                    progress.hide ();
                    handler.show ().text ('保存失败');
                }
            } finally {
                progress.hide ();
            }
        } else if (type === 'module') {
            project = settings.project;
            if (!('modules' in project)) {
                project.modules = {};
            }
            handler.hide ();
            progress.show ();
            let module = {name: name, path: path, pattern: pattern, projectId: project.id};
            try {
                let id = bridge.require ('save-module', module);
                if (id) {
                    delete module.projectId;
                    create_and_fill_module (project.modules [name] = module);
                    editor.modal ('hide');
                } else {
                    progress.hide ();
                    handler.show ().text ('保存失败');
                }
            } finally {
                progress.hide ();
            }
        }
    });
/*
    // 基于准备好的dom，初始化echarts实例
    let myChart = echarts.init(document.getElementById('chart-project'), null, {renderer: 'svg'});
    // 指定图表的配置项和数据
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption (create_option ());
*/
});

// ------------------------------- private functions -------------------------------------
function fill_project (project) {
    if (!project) return;
    project_pane.show ();
    $('#project-name').text (project.name);
    $('#project-path').text (project.path);
    $('.list-header').text (project.name);

    if ('modules' in project) {
        for (let k in project.modules) if (project.modules.hasOwnProperty (k)) {
            create_and_fill_module (project.modules[k]);
        }
    }
    toolbar.enable ();
}

function create_and_fill_module (module) {
    let list = $('#module-list').show ();
    let li = $('<li/>').attr ('data-name', module.name).appendTo (list);
    let div = $('<div class="module-info flexable"/>').appendTo (li);
    $('<h4/>').text (module.name).appendTo (div);
    $('<div/>').text (module.path).appendTo (div);
    // $('<div class="canvas" />').appendTo (li);

    list = $('#nav-module-list').show ();
    li = $('<li/>').attr ('data-name', module.name).appendTo (list);
    let a = $('<a class="module-item"/>').appendTo (li);
    $('<i class="fa fa-fw fa-angle-right" />').appendTo (a);
    $('<span />').text (module.name).appendTo (a);
}

function close_project () {
    try {
        bridge.require ('close-project');
        project_pane.hide ();
        $ ('#project-name').text ('');
        $ ('#project-path').text ('');
        $ ('.list-header').text ('');

        $ ('.module-name-list').empty ().hide ();
        $ ('#module-list').empty ().hide ();

        if ('project' in settings) {
            delete settings.project;
        }

        for (let k in settings.charts) if (settings.charts.hasOwnProperty (k)) {
            let chart = settings.charts[k];
            chart.dispose ();
        }
        settings.charts = {};
        toolbar.reset ();
    } catch (E) {
        alert (E);
    }
}

function choose_projects () {
    try {
        let data = bridge.require ('projects');
        let pane = $('#choose-projects-body').empty ();
        if (data && data.length) {
            let ul = $('<ul class="form-list"/>').appendTo (pane);
            data.forEach (item => {
                $('<li class="list-item flexable"/>').attr ('data-pid', item.id)
                    .text (item.name).on ('click', select_project).appendTo (ul);
            });
        }
        project_selector.modal ('show');
    } catch (E) {
        alert (E);
    }
}

function open_editor (self) {
    let type = settings.editing_type = $(self).attr ('data-type'), projectId;
    if ('project' in settings) {
        projectId = settings.project.id;
    }
    if (type === 'module' && !projectId) {
        alert ('没有项目');
    } else {
        editor.modal ('show');
    }
}

function select_project () {
    $('.form-list').find ('.list-item').removeClass ('selected');
    $(this).addClass ('selected');
}

function update_ui () {
    let W = $(window).outerWidth (), H = $(window).outerHeight ();
    set_size (W, H);
}

function set_size (width, height) {
    $('.content-root').css ({width: width, height: height});
}

function create_option () {
    return {
        tooltip: {
            trigger: 'item'
        },
        legend: {
            top: 'center',
            left: 300,
            orient: 'vertical'
        },
        series: [
            {
                type: 'pie',
                radius: ['45%', '95%'],
                center: [150, 'center'],
                avoidLabelOverlap: true,
                label: {
                    show: false,
                    position: 'center',
                    formatter: "{b}: {c}({d}%)",
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '20',
                        fontWeight: 'bold'
                    }
                }
            }
        ]
    };
}

$(window).on ('resize', update_ui);